import cfg
import os
import time
import fnmatch
import job
import tag

def get_cnd_dir(odate=''):
	if not odate:
		odate=time.strftime("%Y%m%d")
	assert len(odate)==8
	cnd_dir = os.path.join(cfg.cnd_root_dir,odate)
	if not os.path.exists(cnd_dir):
		os.makedirs(cnd_dir)
	return cnd_dir

def filepath(cnd_name='',odate=''):
	cnd_name = cnd_name.lower()
	cnd_dir = get_cnd_dir(odate)
	return os.path.join(cnd_dir,cnd_name)

def add(name,odate=''):
	cnd_path = filepath(name,odate)
	open(cnd_path,"w")

def clear(name,odate=''):
	name=name.lower()
	cnd_dir = get_cnd_dir(odate)
	cnd_path = os.path.join(cnd_dir,name)
	try:
		os.remove(os.path.join(cnd_dir,name))
	except Exception,e:
		pass

def list(odate='',prefix='',type='',strip=False):
	prefx=prefix.lower()
	type=type.lower()
	cnd_dir = get_cnd_dir(odate)
	cnd_list = [x.lower() for x in os.listdir(cnd_dir)]
	if prefix:
		cnd_list = [x for x in cnd_list if x.find(prefix)==0]
	if type:
		cnd_list = [x for x in cnd_list if x.split('.')[-1]==type]
	if strip:
		cnd_list = tuple(set([x.split('.')[0] for x in cnd_list]))
	return cnd_list

def dates():
	date_list = os.listdir(cfg.cnd_root_dir)
	return [x for x in date_list if len(x)==8]

def exists(cnd_name='',odate=''):
	cnd_path = filepath(cnd_name,odate)
	return os.path.exists(cnd_path)

def clear_all(odate='',pattern='*'):
	cnd_dir = get_cnd_dir(odate)
	for name in os.listdir(cnd_dir):
		if fnmatch.fnmatch(name,pattern):
			os.remove(os.path.join(cnd_dir,name))
	if pattern=='*':
		os.rmdir(cnd_dir)

def by_type(date,tags=[]):
	out = {}
	out['ignore'] = set(list(date,type='ignore',strip=True))
	out['order'] = set(list(date,type='order',strip=True))
	out['error'] = set(list(date,type='error',strip=True))
	out['sleep'] = set(list(date,type='sleep',strip=True))
	out['run'] = set(list(date,type='run',strip=True))
	out['ok'] = set(list(date,type='ok',strip=True))
	out['todo']  = out['order']-out['ok']-out['ignore']
	out['active'] = out['run']-out['ok']-out['error']-out['sleep']
	out['error'] = out['error']-out['ignore']
	if tags:
		tags = set(tags)
		jobs_with_tags = tag.jobs_with_tags(tags)
		out['order'] &= jobs_with_tags
		out['error'] &= jobs_with_tags
		out['sleep'] &= jobs_with_tags
		out['run'] &= jobs_with_tags
		out['ok'] &= jobs_with_tags
		out['ignore'] &= jobs_with_tags
		out['todo'] &= jobs_with_tags
		out['active'] &= jobs_with_tags
	return out

def stat(date):
	out = {}
	for k,v in by_type(date).items():
		out[k]=len(v)
	return out

def time_mod(name,date):
	fp = filepath(name,date)
	return os.stat(fp)[8] # 7=accessed 8=modified 9=created

def active_cnt(name):
	out = set()
	for d in dates():
		if exists(name+'.run',d) and not exists(name+'.ok',d) and not exists(name+'.error',d):
			out.add(d)
	return out

if __name__=="__main__":
	from pprint import pprint
	cfg.cnd_root_dir=r"Y:\riv_prod\cnd"
	print time_mod('auto.ok','20120220')
